package com.aiguigu.locks;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockDemo {
    static Lock lockA=new ReentrantLock();
    static Lock lockB=new ReentrantLock();
    public static void main(String[] args) {
        //lock版
       /* new Thread(()->{
            lockA.lock();
            try {
                System.out.println(Thread.currentThread().getName()+"自己持有锁A,尝试抢锁B");
                lockB.lock();
                try{
                    System.out.println(Thread.currentThread().getName()+"抢锁B中======");
                    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                }finally {
                    lockB.unlock();
                }
            } finally {
                lockA.unlock();
            }
        },"A").start();
        new Thread(()->{
            lockB.lock();
            try{
                System.out.println(Thread.currentThread().getName()+"自己持有锁B,尝试抢锁A");
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                lockA.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"抢锁A=====");
                }finally{
                    lockA.unlock();
                }
            }finally{
                lockB.unlock();
            }
        },"B").start();*/

        //synchronized
        new Thread(()->{
            synchronized(lockA){
                System.out.println(Thread.currentThread().getName()+"自己持有锁A,尝试抢锁B");
                synchronized(lockB){
                    System.out.println(Thread.currentThread().getName()+"抢锁B中======");
                }
            }
        },"A").start();
        new Thread(()->{
            synchronized(lockB){
                System.out.println(Thread.currentThread().getName()+"自己持有锁A,尝试抢锁B");
                synchronized(lockA){
                    System.out.println(Thread.currentThread().getName()+"抢锁B中======");
                }
            }
        },"B").start();
    }
}
